<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var arr = function (ideas) {
      const ilen = ideas.length;
      if (ilen < 2) return 0;
      //所有存在的字符串，减少搜索次数
      let sets = new Set();
      for (const idea of ideas) {
        sets.add(idea);
      }
      //保存从首字母i变到j之后，有多少满足条件的单词
      let cnt = new Array(26).fill(0).map(() => new Array(26).fill(0));
      for (const idea of ideas) {
        let a = idea.charCodeAt(0) - 'a'.charCodeAt();
        let str = idea;
        for (let i = 0; i < 26; i++) {
          if (i == a) continue;
          let char = String.fromCharCode(i + 'a'.charCodeAt());
          str = char + str.slice(1);
          if (!sets.has(str)) {
            cnt[a][i]++;
          }
        }
      }
      let ans = 0;
      //统计所有到i到j和j到i的乘积
      for (let i = 0; i < 26; i++) {
        for (let j = 0; j < 26; j++) {
          ans += cnt[i][j] * cnt[j][i];
        }
      }
      return ans;
    };
    console.log(arr(ideas = ["coffee", "donuts", "time", "toffee"]));
  </script>
</body>

</html>